package com.chen.gift.controller;

import com.chen.gift.service.IPostService;
import com.chen.gift.domain.Post;
import com.chen.gift.query.PostQuery;
import com.chen.gift.util.AjaxResult;
import com.chen.gift.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/post")
public class PostController {

    @Autowired
    public IPostService postService;

    /**
     * 保存和修改公用的
     * @param post  传递的实体
     * @return AjaxResult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Post post){
        try {
            if( post.getId()!=null)
                postService.updateById(post);
            else
                postService.insert(post);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("保存对象失败！"+e.getMessage());
        }
    }

    /**
    * 删除对象信息
    * @param id 根据id删除数据
    * @return AjaxResult转换结果
    */
    @DeleteMapping(value="/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            postService.deleteById(id);
            return AjaxResult.me();
        } catch (Exception e) {
        e.printStackTrace();
            return AjaxResult.me().setMessage("删除对象失败！"+e.getMessage());
        }
    }

    /**
    * @param id 根据id获取用户
    * @return 返回根据id获取的用户
    */
    @GetMapping("/{id}")
    public AjaxResult get(@PathVariable("id")Long id) {
        try {
            Post post = postService.selectById(id);
            return AjaxResult.me().setResultObj(post);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("获取一个失败！"+e.getMessage());
        }
    }


    /**
    * 查看所有的员工信息
    * @return 所有员工数据
    */
    @GetMapping
    public AjaxResult list(){
        try {
            List< Post> list = postService.selectList(null);
            return AjaxResult.me().setResultObj(list);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("获取所有失败！"+e.getMessage());
        }
    }

    /**
    * 分页查询数据
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping("/list")
    public AjaxResult json(@RequestBody PostQuery query) {
        try {
            Page<Post> page = new Page<>(query.getPage(),query.getRows());
            page = postService.selectPage(page);
            PageList<Post> pageList = new PageList<>(page.getTotal(),page.getRecords());
            return AjaxResult.me().setResultObj(pageList);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("获取分页数据失败！"+e.getMessage());
        }

    }
}
